import Vue from "vue";
import Vuex from 'vuex';
import createLogger from 'vuex/dist/logger';
import api from '@/api';
Vue.use(Vuex);

// 开发环境中：我们基于logger插件，在控制台输出派发日志，方便调试
let env = process.env.NODE_ENV,
    plugins = [];
if (env === 'development') plugins = [createLogger()];

// 创建STORE
const store = new Vuex.Store({
    state: {
        list: null
    },
    mutations: {
        // 同步修改状态值(全部任务)
        queryAllTask(state, list) {
            state.list = list;
        },
        // 删除任务
        deleteTaskById(state, id) {
            let { list } = state;
            if (list == null) return;
            state.list = list.filter(item => +item.id !== +id);
        },
        // 修改任务
        updateTaskById(state, id) {
            let { list } = state;
            if (list == null) return;
            state.list = list.map(item => {
                if (+item.id === +id) {
                    item.state = 2;
                    item.complete = new Date().toLocaleString('zh-CN', { hour12: false });
                }
                return item;
            });
        }
    },
    actions: {
        // 异步获取全部任务列表,同步到vuex中
        async queryAllTaskAsync({ commit }) {
            let { code, list } = await api.getTaskList(0);
            if (+code !== 0) list = [];
            commit('queryAllTask', list);
            return list;
        }
    },
    plugins
});
export default store;